//
//  WJCSuitTableViewController.m
//  花絮
//
//  Created by WJC mac on 2021/10/6.
//

#import "WJCSuitTableViewController.h"

#import "NSObject+KVCChangeType.h"
#import "MJRefresh.h"
#import "NSObject+FCUrlPathGet.h"
#import "Masonry.h"
#import "SVProgressHUD.h"
@interface WJCSuitTableViewController ()<UITextFieldDelegate,FCSuitBoundTableViewDelegate>
@property (strong, nonatomic) NSString * keyword;
@property (strong, nonatomic) NSMutableArray * allObj;
@end

@implementation WJCSuitTableViewController
-(UIView *)searchBackView{
    if (!_searchBackView) {
        _searchBackView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, WJCScreenW, 48)];
        _searchBackView.backgroundColor = HEXC(0xF5F5F5);
    }
    return _searchBackView;;
}
-(void)setAddsearchBar:(BOOL)addsearchBar{
    _addsearchBar = addsearchBar;
    
    if (addsearchBar) {
      
        self.searchBar = [[FCCSearchBar alloc] initWithFrame:CGRectMake(8, 4, WJCScreenW-16, 38)];
//        self.searchBar.backgroundColor =  HEXC(0xF5F5F5);
        [self.searchBackView addSubview:self.searchBar];
        [self.view addSubview:self.searchBackView];
        self.searchBar.delegate = self;
        
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(48);
            make.left.and.bottom.and.right.mas_equalTo(0);
        }];
        WJCWeakSelf
        self.tableView.tableViewDidScroll = ^(FCSuitBoundTableView * _Nonnull tableView) {
            [weakSelf.view endEditing:YES];
        };
    }else{
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.and.left.and.bottom.and.right.mas_equalTo(0);
        }];
    }
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    if (!self.allObj||self.allObj.count<1) {
        self.allObj = self.tableView.contentModelArr;
    }
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    NSString * toBeString = [textField.text.length>0?textField.text:@"" stringByReplacingCharactersInRange:range withString:string];
    self.keyword = toBeString;
    if (self.searchReauest) {
        if (toBeString.length>0) {
            NSMutableArray *array = [NSMutableArray new];
            NSArray *arr = [self.searchReauest componentsSeparatedByString:@","];
            for (id contentObj in self.allObj) {
                for (NSString *st in arr) {
                    if ([st containsString:@"."]) {
                        NSArray *subArr = [st componentsSeparatedByString:@"."];
                        id ob = contentObj;
                        for (NSString *s in subArr) {
                            
                            if ([ob checkIsExistPropertyWithInstance:ob verifyPropertyName:s andLogAllProperty:NO]) {
                                ob = [ob valueForKey:s];
                            }
                        }
                        if([ob isKindOfClass:[NSString class]]){
                            NSString *str =ob;
                            if ([str containsString:toBeString]&&![array containsObject:contentObj]) {
                                [array addObject:contentObj];
                            }
                        }
                    }else{
                    if ([contentObj checkIsExistPropertyWithInstance:contentObj verifyPropertyName:st andLogAllProperty:NO]) {
                        if ([[contentObj valueForKey:st] isKindOfClass:[NSString class]]) {
                            NSString *str =[contentObj valueForKey:st];
                            if ([str containsString:toBeString]&&![array containsObject:contentObj]) {
                                [array addObject:contentObj];
                            }
                        }
                    }else if([contentObj isKindOfClass:[NSDictionary class]]){
                        if ([[contentObj valueForKey:st] isKindOfClass:[NSString class]]) {
                            NSString *str =[contentObj valueForKey:st];
                            if ([str containsString:toBeString]&&![array containsObject:contentObj]) {
                                [array addObject:contentObj];
                            }
                        }
                    }
                    }
                }
                
            }
            self.tableView.contentModelArr = array;
        }else{
            self.tableView.contentModelArr = self.allObj;
        }
        
        [self.tableView reloadData];
    }else if (self.searchKey.length>0){
        [self loadNewData];
    }
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView = [[FCSuitBoundTableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.tableView.frame = CGRectMake(0, 0, WJCScreenW, WJCScreenH);
    self.tableView.backgroundColor =  HEXC(0xF5F5F5);
    self.edgesForExtendedLayout =UIRectEdgeNone;
       self.automaticallyAdjustsScrollViewInsets =NO;
   self.tableView.autoresizingMask =UIViewAutoresizingFlexibleHeight |UIViewAutoresizingFlexibleWidth;
    
    [self.view addSubview:self.tableView];
    self.tableView.emptyImg = [UIImage imageNamed:@"ic_empty"];
    self.tableView.tableViewDelegate = self;
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endRefresh) name:@"refreshEnd" object:nil];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.left.and.bottom.and.right.mas_equalTo(0);
    }];
   
    
}

-(void)endRefresh{
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}
-(void)loadNewData{
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(loadNewdataSourse) object:nil];
       [self performSelector:@selector(loadNewdataSourse) withObject:nil afterDelay:1];
}
-(void)loadNewdataSourse{
    
    if (self.tableView.requestData) {
        NSMutableDictionary *dic = self.tableView.requestData.mutableCopy;
        if (dic[@"pageNum"]) {
            [dic setValue:@(1) forKey:@"pageNum"];
        }
        if(self.showSv){
            [SVProgressHUD show];
        }
        if(self.keyword&&self.searchKey&&self.searchBar.text.length>0){
            [dic setValue:self.keyword forKey:self.searchKey];
        }
        dic.urlPath = self.tableView.urlPath;
        dic.requestData = dic;
        dic.mjClass = self.tableView.mjClass;
        dic.filterError =  self.tableView.filterError;
        dic.requestStrMJClass = self.tableView.requestStrMJClass;
        WJCWeakSelf
        if(self.formDataGet){
            [dic formDataRequestWithlocalSuccessBlock:^(NSArray*  _Nonnull obj) {
                if(!weakSelf.loadNewFinishBlock){
                    if ([obj isKindOfClass:[NSArray class]]) {
                        if(obj.count<1&&!self.exceptEmpTable){
                            weakSelf.tableView.setEmptyView = YES;
                        }
                        weakSelf.tableView.contentModelArr = obj.mutableCopy;
                    }else{
                        if (!obj&&!self.exceptEmpTable) {
                            weakSelf.tableView.setEmptyView = YES;
                        }else{
                            weakSelf.tableView.contentModelArr = @[obj].mutableCopy;
                        }
                    }
                    
                    [weakSelf.tableView reloadData];
                    [weakSelf.tableView.mj_header endRefreshing];
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
            } Block:^(NSArray*  _Nonnull obj) {
                if ([obj isKindOfClass:[NSArray class]]) {
                    if(obj.count<1&&!self.exceptEmpTable){
                        weakSelf.tableView.setEmptyView = YES;
                    }
                    weakSelf.tableView.contentModelArr = obj.mutableCopy;
                }else{
                    if (!obj&&!self.exceptEmpTable) {
                        weakSelf.tableView.setEmptyView = YES;
                    }else{
                        if ((dic[@"pageSize"]&&obj.count<[dic[@"pageSize"] integerValue])||obj.count<10) {
                            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                        }
                        weakSelf.tableView.contentModelArr = @[obj].mutableCopy;
                    }
                }
                if(weakSelf.loadNewFinishBlock){
                    weakSelf.loadNewFinishBlock(weakSelf.tableView,obj);
                }
                [SVProgressHUD dismiss];
                weakSelf.showSv = NO;
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tableView.mj_footer endRefreshing];
            } andFail:^(id  _Nonnull obj) {
                [weakSelf.tableView.mj_header endRefreshing];
                               [weakSelf.tableView.mj_footer endRefreshing];
            }];
//            [dic formDataRequestWithBlock:^(NSArray*  _Nonnull obj) {
//
//                if ([obj isKindOfClass:[NSArray class]]) {
//                    if(obj.count<1){
//                        weakSelf.tableView.setEmptyView = YES;
//                    }
//                    weakSelf.tableView.contentModelArr = obj.mutableCopy;
//                }else{
//                    if (!obj) {
//                        weakSelf.tableView.setEmptyView = YES;
//                    }else{
//                        weakSelf.tableView.contentModelArr = @[obj].mutableCopy;
//                    }
//                }
//
//                [weakSelf.tableView reloadData];
//                [weakSelf.tableView.mj_header endRefreshing];
//                [weakSelf.tableView.mj_footer endRefreshing];
//            } andFail:^(id  _Nonnull obj) {
//                [weakSelf.tableView.mj_header endRefreshing];
//                [weakSelf.tableView.mj_footer endRefreshing];
//            }];
        }else{
            [dic postRequestWithlocalSuccessBlock:^(NSArray*  _Nonnull obj) {
                if(!weakSelf.loadNewFinishBlock){
                    if ([obj isKindOfClass:[NSArray class]]) {
                        if(obj.count<1){
                            weakSelf.tableView.setEmptyView = YES;
                        }
                        weakSelf.tableView.contentModelArr = obj.mutableCopy;
                    }else{
                        if (!obj) {
                            weakSelf.tableView.setEmptyView = YES;
                        }else{
                            weakSelf.tableView.contentModelArr = @[obj].mutableCopy;
                        }
                    }
                    [weakSelf.tableView reloadData];
                    [weakSelf.tableView.mj_header endRefreshing];
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
            } Block:^(NSArray*  _Nonnull obj) {
                            if ([obj isKindOfClass:[NSArray class]]) {
                                if(obj.count<1){
                                    weakSelf.tableView.setEmptyView = YES;
                                }
                                if ((dic[@"pageSize"]&&obj.count<[dic[@"pageSize"] integerValue])||obj.count<10) {
                                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                                }
                                weakSelf.tableView.contentModelArr = obj.mutableCopy;
                            }else{
                                if (!obj) {
                                    weakSelf.tableView.setEmptyView = YES;
                                }else{
                                    if ((dic[@"pageSize"]&&obj.count<[dic[@"pageSize"] integerValue])||obj.count<10) {
                                        [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                                    }
                                    weakSelf.tableView.contentModelArr = @[obj].mutableCopy;
                                }
                            }
                if(weakSelf.loadNewFinishBlock){
                    weakSelf.loadNewFinishBlock(weakSelf.tableView,obj);
                }
                            [weakSelf.tableView reloadData];
                            [weakSelf.tableView.mj_header endRefreshing];
            } andFail:^(id  _Nonnull obj) {
                
            }];
//        [dic postRequestWithBlock:^(NSArray*  _Nonnull obj) {
//            if ([obj isKindOfClass:[NSArray class]]) {
//                if(obj.count<1){
//                    weakSelf.tableView.setEmptyView = YES;
//                }
//                weakSelf.tableView.contentModelArr = obj.mutableCopy;
//            }else{
//                if (!obj) {
//                    weakSelf.tableView.setEmptyView = YES;
//                }else{
//                    weakSelf.tableView.contentModelArr = @[obj].mutableCopy;
//                }
//            }
//            [weakSelf.tableView reloadData];
//            [weakSelf.tableView.mj_header endRefreshing];
//            [weakSelf.tableView.mj_footer endRefreshing];
//        }andFail:^(id  _Nonnull obj) {
//            [weakSelf.tableView.mj_header endRefreshing];
//            [weakSelf.tableView.mj_footer endRefreshing];
//        }];
    }
    }else{
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }
}
-(void)loadMoreData{
    if (self.tableView.requestData&&self.tableView.requestData[@"pageSize"]) {
    NSMutableDictionary *dic = self.tableView.requestData.mutableCopy;
        if(self.keyword&&self.searchKey&&self.searchBar.text.length>0){
            [dic setValue:self.keyword forKey:self.searchKey];
        }
    [dic setValue:@(((int)self.tableView.contentModelArr.count/[dic[@"pageSize"] intValue])+(self.tableView.contentModelArr.count%[dic[@"pageSize"] intValue]>0?2:1)) forKey:@"pageNum"];
        dic.requestData = dic;
        dic.urlPath = self.tableView.urlPath;
        dic.mjClass = self.tableView.mjClass;
        dic.requestStrMJClass = self.tableView.requestStrMJClass;
    WJCWeakSelf
        if(self.formDataGet){
            [dic formDataRequestWithBlock:^(NSArray*  _Nonnull obj) {
                [weakSelf.tableView.contentModelArr addObjectsFromArray:obj];
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_header endRefreshing];
                if ((dic[@"pageSize"]&&obj.count<[dic[@"pageSize"] integerValue])||obj.count<10) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }else{
                [weakSelf.tableView.mj_footer endRefreshing];
                }
            } andFail:^(id  _Nonnull obj) {
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tableView.mj_footer endRefreshing];
            }];
        }else{
    [dic postRequestWithBlock:^(NSArray*  _Nonnull obj) {
        [weakSelf.tableView.contentModelArr addObjectsFromArray:obj];
        if(weakSelf.loadMoreFinishBlock){
            weakSelf.loadMoreFinishBlock(weakSelf.tableView,obj);
        }
        [weakSelf.tableView reloadData];
        [weakSelf.tableView.mj_header endRefreshing];
        if ((dic[@"pageSize"]&&obj.count<[dic[@"pageSize"] integerValue])||obj.count<10) {
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
        [weakSelf.tableView.mj_footer endRefreshing];
        }
    } andFail:^(id  _Nonnull obj) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
        }
    }else{
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
